import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

import 'winston-daily-rotate-file';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { ConfigService } from '@nestjs/config';
import {
  ValidationPipe,
  VERSION_NEUTRAL,
  VersioningType,
} from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  const _port = process.env.PORT ?? 3000;
  const port: number | string = configService.get('PORT', _port);
  const errorFilterFlag = configService.get<string>('ERROR_FILTER');
  const cors = configService.get<string>('CORS', 'false');
  const prefix = configService.get<string>('PREFIX', '/api');
  const versionStr = configService.get<string>('VERSION');
  let version: any[] = [];
  if (versionStr) {
    version = versionStr.split(',');
  }
  app.setGlobalPrefix(prefix);
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  app.enableShutdownHooks(); //  开启生命周期 避免强制终止​​导致的未完成操作
  app.useGlobalPipes(
    // 应用类的校验功能
    new ValidationPipe({
      whitelist: true, // 开启未在dto校验规则里的字段，则遗弃掉，开发环境可以设置为false
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );
  app.enableVersioning({
    // 设置版本
    type: VersioningType.URI,
    defaultVersion: version.length ? version : VERSION_NEUTRAL,
  });
  if (cors === 'true') {
    // 开启跨域
    app.enableCors();
  }
  if (errorFilterFlag === 'true') {
    const httpAdapter = app.get(HttpAdapterHost);
    app.useGlobalFilters(new AllExceptionFilter(httpAdapter));
  }

  await app.listen(port);
  // logger.log(`App 运行在：${port}端口`);
}
bootstrap();
